<?php
    require_once('includes/common.inc.php');

    define("MAX_THUMBNAIL_SIZE", 118);
    define("CLIENTS_PHOTO_PATH", "upload/clients_photo/");


    $error = "";
    $photoLink = "";
    $tmpFilePath = "";

    foreach ($_FILES as $uploadedFileInfo)
    {
        $tmpFilePath = $uploadedFileInfo['tmp_name'];
        $realFileName = $uploadedFileInfo['name'];
        $fileExtension = File::GetFileExtension($realFileName);
        switch ($fileExtension)
        {
            case "jpg":
            case "jpeg":
                $img = imagecreatefromjpeg($tmpFilePath);
                break;
            case "png":
                $img = imagecreatefrompng($tmpFilePath);
                break;
            case "gif":
                $img = imagecreatefromgif($tmpFilePath);
                break;
            default:
                $error = "Файл имеет недопутимое расширение: " . $fileExtension . "\n Допустимые расширения: jpg(jpeg), png, gif";
                break;
        }
        if (isset($img))
        {
            $newImageName = CLIENTS_PHOTO_PATH . GetRandomString('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 8) . ".png";
            $newImagePath = ROOT_PATH . $newImageName;
            list($width, $height) = getimagesize($tmpFilePath);
            if (($width > MAX_THUMBNAIL_SIZE) || ($height > MAX_THUMBNAIL_SIZE))
            {
                if ($width > $height)
                {
                    $aspect = $height / $width;
                    $newWidth = MAX_THUMBNAIL_SIZE;
                    $newHeight = $newWidth * $aspect;
                }
                else
                {
                    $aspect = $width / $height;
                    $newHeight = MAX_THUMBNAIL_SIZE;
                    $newWidth = MAX_THUMBNAIL_SIZE * $aspect;
                }
                $thumbnail = imagecreatetruecolor($newWidth, $newHeight);
                imagecopyresized($thumbnail, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                imagepng($thumbnail, $newImagePath);
            }
            else
            {
                imagepng($img, $newImagePath);
            }
            $photoLink = "/" . $newImageName;
        }
    }

    echo json_encode(array(
        "error" => $error,
        "photo_link" =>$photoLink
    ));

    function GetRandomString($valid_chars, $length)
    {
        $random_string = "";
        $num_valid_chars = strlen($valid_chars);
        for ($i = 0; $i < $length; $i++)
        {
            $random_pick = mt_rand(1, $num_valid_chars);
            $random_char = $valid_chars[$random_pick-1];
            $random_string .= $random_char;
        }
        return $random_string;
    }
